package com.library.common.gdxx;

import com.library.common.config.PushConfig;
import com.library.common.utils.sign.Md5Utils;
import com.library.common.utils.uuid.UUID;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Package: com.library.common.gdxx
 * @ClassName: SignHandle
 * @Author: Yin
 * @Date: 11:38
 * @Description: 签名处理（GDXX Sign）
 */
@Component
public final class SignHandle {

    @Resource
    private PushConfig config;

    /**
     * 处理请求时需要的请求头和签名
     * @param body 请求参数
     * @return map 键值对，里面存在请求头和签名相关信息
     */
    public HttpHeaders handle(String body) {
        Long timestamp = System.currentTimeMillis();
        // 32 位
        String nonce = UUID.fastUUID().toString(true);
        // 签名字串
        // MD5
        String signStr =
            "appid=" + config.getAppId() + "#" +
            "secret=" + config.getSecret() + "#" +
            "nonce=" + nonce + "#" +
            "timestamp=" + timestamp + "#" +
            body;
        String sign = Md5Utils.hash(signStr);
        // 请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("x-gdxx-timestamp",timestamp.toString());
        httpHeaders.set("x-gdxx-nonce", nonce);
        httpHeaders.set("x-gdxx-appid",config.getAppId());
        httpHeaders.set("x-gdxx-sign", sign);
        httpHeaders.set("Content-Type","application/json; charset=UTF-8");
        return httpHeaders;
    }

}
